
import { registerClass } from "../../../cfw/tools/class_decorator";
import { SDKDir, SDKState } from "../../SDKDefine";
import BaseAd from "../../core/base/BaseAd";
/**
 * 1091+
 * 注意：原生模板广告实例不能复用，每次需要重新加载时要重新create
    注意：广告对象长时间不用会被回收，需要重新创建
 */
@registerClass('VivoCustomAd')
export default class VivoCustomAd extends BaseAd {

    open() {

        this.create();
        this.show();
    }
    create() {
        this.destroy()
        if (!this.ad) {
            this.ad = this.sdk.createCustomAd({
                posId: this.adUnitID,
                style: this.getStyle(),
            });
            this.ad.onError(this.getFunc(this.onError));
            this.ad.onClose(this.getFunc(this.onClose));
            this.ad.onLoad(this.getFunc(this.onLoad));
            this.ad.onHide(this.getFunc(this.onHide));
        }

    }

    getSize() {
        let size = this.system.getVisibleSize()
        // let r = size.height > size.width
        var defaultSize = (size.height / size.width) ? { height: 1280, width: 720 } : { width: 1280, height: 720 }
        let width = 720 * ((size.height / size.width) > (defaultSize.height / defaultSize.width) ? size.width / defaultSize.width : size.height / defaultSize.height);
        return width;
    }

    getStyle() {
        let r = 720 / 525;
        let sys = this.sdk.getSystemInfoSync()
        this.style.width = this.getSize();
        this.style.height = this.style.width / r;
        console.log(' r ', r, ' sys.screenWidth  ', sys.screenWidth, ' width ', this.style.width, ' height ', this.style.height)
        let size = this.system.getVisibleSize()
        switch (this.param.dir) {
            case SDKDir.MID:
                return {
                    left: (size.width - this.style.width) / 2 * this.system.getClientScaleX(),
                    top: (size.height - this.style.height) / 2 * this.system.getClientScaleY()
                }
            case SDKDir.BOTTOM_MID:
                return {
                }
            default:
                return {
                }

        }

    }



    show() {
        if (this.ad) {
            this.ad.show().then(() => {
                console.log('原生模板广告展示完成');
                this.setState(SDKState.loadSucess)
            }).catch((err) => {
                console.log('原生模板广告展示失败', JSON.stringify(err));
                this.setState(SDKState.loadFail)
            })
        }
    }


    destroy() {
        if (this.ad) {
            this.ad.offError(this.getFunc(this.onError));
            this.ad.offClose(this.getFunc(this.onClose));
            this.ad.offLoad(this.getFunc(this.onLoad));
            this.ad.offHide(this.getFunc(this.onHide));
            this.ad.destroy();
            this.ad = null;
        }
    }

    onClose() {

    }

    onHide() {

    }

    close() {
        if (this.ad) {
            this.ad.hide()
        }
    }
}